﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
//using System.Web.Configuration;

namespace MyTime.ProviderFactory.ProviderHelpers
{
    public class MyTimeProviderManager
    {
        private static MyTimeProviderBase defaultProvider;
        private static MyTimeProviderCollection providers;
        private static ProviderSettingsCollection _providerSettings;

        static MyTimeProviderManager()
        {
            Initialize();
        }

        private static void Initialize()
        {
            MyTimeProviderConfiguration configuration = (MyTimeProviderConfiguration)ConfigurationManager.GetSection("MyTimeProvider");

            if (configuration == null)
                throw new ConfigurationErrorsException("MyTimeProviderManager configuration section is not set correctly.");

            providers = new MyTimeProviderCollection();

            foreach (ProviderSettings provider in configuration.Providers)
            {
                var type = Type.GetType(provider.Type);
                if (type == null)
                {
                    throw new Exception(string.Format("Can't load type: {0}", provider.Type));
                }
                var obj = Activator.CreateInstance(type) as MyTimeProviderBase;
                //obj.Initialize(obj.Name, ConfigurationManager.AppSettings);
                obj.Initialize(obj.Name, provider.Parameters);
                obj.Settings = provider.Parameters;
                providers.Add(obj);
            }
            _providerSettings = configuration.Providers;
            providers.SetReadOnly();
            defaultProvider = providers[configuration.Default];
            if (defaultProvider == null)
                throw new Exception("defaultProvider not found");
        }


        public static MyTimeProviderBase Provider
        {
            get
            {
                return defaultProvider;
            }
        }

        public static MyTimeProviderCollection Providers
        {
            get
            {
                return providers;
            }
        }
        public static ProviderSettingsCollection ProviderSettings
        {
            get
            {
                return _providerSettings;
            }
        }
    }
}
